package com.sky.service.user.impl;

import com.sky.constant.StatusConstant;
import com.sky.mapper.user.UserDishFlavorMapper;
import com.sky.mapper.user.UserDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.service.user.UserDishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDishServiceImpl implements UserDishService {
    @Autowired
    private UserDishMapper userDishMapper;
    @Autowired
    private UserDishFlavorMapper userDishFlavorMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<DishVO> findByCategoryId(Long categoryId) {

        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get("Dish-" + categoryId);
        if(!CollectionUtils.isEmpty(dishVOList)){
            log.info("从Redis查询");
            return dishVOList;
        }
        log.info("从数据库查询");
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> dishList = userDishMapper.findByCategoryId(dish);

        dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = userDishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        //写到Redis
        redisTemplate.opsForValue().set("Dish-" + categoryId, dishVOList);
        return dishVOList;
    }
}
